// const ip_address = "8.137.123.185:8081";  
const ip_address = "www.gynshwechat.cn";
// www.gynshwechat.cn
// const ip_address = "127.0.0.1:8001";
const retitle = "https";
const ip_port = "8001";  
const APIkey = "7IDBZ-7JDW7-BFQX4-HVPNI-YEVCO-JCFEY";


function changeMyInfo(openid,todoType,value) {
  return new Promise((resolve, reject) => {
    wx.request({
      // http://localhost:8001/institution/getByCityName?cityname=成都市
      url: retitle+"://"+ ip_address + "/user/changeMyInfo",
      // data: JSON.stringify(formData),  // 将 formData 转化成JSON对象
      method: 'POST',
      header: {
        'Content-Type':  'application/x-www-form-urlencoded'
      }, // http 请求是 JSON 数据格式
      data:{
        openid:openid,
        todoType:todoType,
        value:value
      },
      success: function (res) {
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getAllByAreaName(cityname,areaname) {
  return new Promise((resolve, reject) => {
    wx.request({
      // http://localhost:8001/institution/getByCityName?cityname=成都市
      url: retitle+"://"+ ip_address + "/institution/getAllByAreaName",
      // data: JSON.stringify(formData),  // 将 formData 转化成JSON对象
      method: 'POST',
      header: {
        'Content-Type':  'application/x-www-form-urlencoded'
      }, // http 请求是 JSON 数据格式
      data:{
        cityname:cityname,
        areaname:areaname
      },
      success: function (res) {
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getInstDatabyInstName(InstName) {
  return new Promise((resolve, reject) => {
    wx.request({
      // http://localhost:8001/institution/getByCityName?cityname=成都市
      url: retitle + "://" + ip_address + "/institution/getByInstName?InstName=" + InstName,
      // data: JSON.stringify(formData),  // 将 formData 转化成JSON对象
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }, // http 请求是 JSON 数据格式
      success: function (res) {
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getInstDatabyName(city_name) {
  return new Promise((resolve, reject) => {
    wx.request({
      // http://localhost:8001/institution/getByCityName?cityname=成都市
      url: retitle+"://"+ ip_address + "/institution/getByCityName?cityname=" + city_name,
      // data: JSON.stringify(formData),  // 将 formData 转化成JSON对象
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }, // http 请求是 JSON 数据格式
      success: function (res) {
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getATMByCityName(city_name) {
  return new Promise((resolve, reject) => {
    wx.request({
      // http://localhost:8001/institution/getByCityName?cityname=成都市
      url: retitle+"://"+ ip_address + "/institution/getATMByCityName?cityname=" + city_name.slice(0,-1),
      // data: JSON.stringify(formData),  // 将 formData 转化成JSON对象
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }, // http 请求是 JSON 数据格式
      success: function (res) {
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getInstDatabyid(city_id, county_id) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://"+ ip_address + "/institution/getByCityCountyId?city=" + city_id + "&county=" + county_id,
      // data: JSON.stringify(formData),  // 将 formData 转化成JSON对象
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }, // http 请求是 JSON 数据格式
      success: function (res) {
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getAllData() {
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/institution/getAllData",
      // data: JSON.stringify(formData),  // 将 formData 转化成JSON对象
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }, // http 请求是 JSON 数据格式
      success: function (res) {
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function Rad(d) { //根据经纬度判断距离
  return d * Math.PI / 180.0;
}
/**
 * 
 * @param {定位纬度} lat1 
 * @param {定位经度} lng1 
 * @param {位置纬度} lat2 
 * @param {位置经度} lng2 
 */
function getDistance(lat1, lng1, lat2, lng2) {
  var radLat1 = this.Rad(lat1);
  var radLat2 = this.Rad(lat2);
  var a = radLat1 - radLat2;
  var b = this.Rad(lng1) - this.Rad(lng2);
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  s = s.toFixed(1) //保留两位小数
  return s
}

function getDistance2(lat1, lng1, lat2, lng2) {
  let longitude = lng2;
  let latitude = lat2;
  let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
  let x = longitude - 0.0065;
  let y = latitude - 0.006;
  let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
  let wz = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
  let lon = z * Math.cos(wz);
  let lat = z * Math.sin(wz);
  longitude=lon;
  latitude=lat;
  lng2 = longitude;
  lat2 = latitude;
  var radLat1 = this.Rad(lat1);
  var radLat2 = this.Rad(lat2);
  var a = radLat1 - radLat2;
  var b = this.Rad(lng1) - this.Rad(lng2);
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  s = s.toFixed(1) //保留两位小数
  return s
}
// 两点间距离lat1,  lng1,  lat2,  lng2
function getMapDistanceApi(lat1, lng1, lat2, lng2) {
  var radLat1 = lat1 * Math.PI / 180.0;
  var radLat2 = lat2 * Math.PI / 180.0;
  var a = radLat1 - radLat2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137; // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000;
  s = s.toFixed(3) //保留两位小数
  s = s * 1000
  console.log(s + "m");
  return s; //返回的米
}

function getAddressByKey(latitude, longitude) {
  return new Promise((resolve, reject) => {
    wx.request({
      //    https://apis.map.qq.com/ws/geocoder/v1/?location=32.906222,101.694803&key=7IDBZ-7JDW7-BFQX4-HVPNI-YEVCO-JCFEY&get_poi=1
      url: "https://apis.map.qq.com/ws/geocoder/v1/?location=" + latitude + "," + longitude + "&key=" + APIkey + "&get_poi=1",
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }, // http 请求是 JSON 数据格式
      success: function (res) {
        console.log("反地址解析成功")
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

function getInstDatabyid2(city_id, county_id){
  let _this = this;
  wx.request({
    url: retitle+"://" +ip_address+"/institution/getByCityCountyId?city="+city_id+"&county="+county_id,
    // data: JSON.stringify(formData),  // 将 formData 转化成JSON对象
    method: 'GET',
    header: {'Content-Type': 'application/json'},  // http 请求是 JSON 数据格式
    success: function (res) {
      let real_networkList = []
      let networkList = res.data;
      networkList.map( (item,index) => {
        if (item.telephone.length>0)
          real_networkList.push(item);
      })
      _this.setData({
        networkList : real_networkList
      })
      _this.getMyLocation(real_networkList)
    }
  })
}

function call_phone(res) {
  let data = res.currentTarget.dataset
  wx.showModal({
    title: "提示",
    content: "拨打 "+data.telephone+" ?",
    complete: (res) => {
      if (res.cancel) {
        return
      }
      if (res.confirm) {
        wx.makePhoneCall({
          phoneNumber: data.telephone,
          success: function () {
            console.log("拨打电话成功！")
          },
          fail: function () {
            console.log("拨打电话失败！")
          }
        })
      }
    }
  })
}

function errorNotice(res){
  wx.showToast({
      title: "因数据安全考虑\r\n目前暂不开放该功能",
      icon: 'none',
      duration: 2000
    })
}

function searchNotice(res){
  wx.showToast({
    title: "敬请期待\r\n请先在主页搜索",
    icon: 'none',
    duration: 2000
  })
}

function getAllDays4Month(year, month){
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/book/getAllDays4Month?year="+year+"&month="+month,
      method: 'GET',
      header: {'Content-Type': 'application/json'},  // http 请求是 JSON 数据格式
      success: function (res) {
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

function submitbook(uid, idcard,uname,telnum,amount,btype,bdesc,year,month,day,map_id){
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/book/submitBook",
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        "uid": uid,
        "idcard": idcard,
        "uname":uname,
        "telnum":telnum,
        "amount":amount,
        "btype":btype,
        "bdesc":bdesc,
        "year":year,
        "month":month,
        "day":day,
        "map_id":map_id,
      },
      success: function (res) {
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

function getOpenid(code){
  const accInfo = wx.getAccountInfoSync().miniProgram;
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/user/getOpenid",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        code: code,
        appid : accInfo.appId
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getToken(code){
  const accInfo = wx.getAccountInfoSync().miniProgram;
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/user/getToken",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        appid : accInfo.appId
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getUserInfo(code){
  const accInfo = wx.getAccountInfoSync().miniProgram;
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/user/getUserInfo",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        appid: accInfo.appId,
        code: code
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}
function getPhoneInfo(code,token){
  const accInfo = wx.getAccountInfoSync().miniProgram;
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/user/getPhoneInfo",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        code: code,
        token: token
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}


function judgeUser(openid,last_login_location){
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/user/judgeUser",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        openid: openid,
        last_login_location:last_login_location
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function registerUser(uname,telnum,idcard,openid,register_location){
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/user/registerUser",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        uname:uname,
        telnum:telnum,
        idcard:idcard,
        openid: openid,
        register_location:register_location
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getBookInfo(openid,status){
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/book/getBookInfo",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        openid:openid,
        status:status
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function cancelBook(bookid){
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/book/cancelBook",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        bookid:bookid
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function adToFavor(map_id,openid){
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/book/adToFavor",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        map_id:map_id,
        openid:openid
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getFavorList(openid){
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/book/getFavorList",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        openid:openid
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function judgeFavor(map_id,openid){
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/book/judgeFavor",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        map_id:map_id,
        openid:openid
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

function getMyInfo(openid){
  return new Promise((resolve, reject) => {
    wx.request({
      url: retitle+"://" + ip_address + "/user/getMyInfo",
      method: 'POST',
      header:{
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data:{
        openid:openid
      },
      success:(res)=>{
        resolve(res);
      },
      fail(err) {
        reject(err)
      }
    })
  });
}

module.exports = {
  changeMyInfo:changeMyInfo,
  getAllByAreaName:getAllByAreaName,
  getInstDatabyName: getInstDatabyName,
  getATMByCityName: getATMByCityName,
  getInstDatabyid:getInstDatabyid,
  getAllData:getAllData,
  Rad:Rad,
  getMapDistanceApi:getMapDistanceApi,
  getDistance:getDistance,
  getAddressByKey:getAddressByKey,
  call_phone:call_phone,
  searchNotice:searchNotice,
  errorNotice:errorNotice,
  getInstDatabyid2:getInstDatabyid2,
  getInstDatabyInstName:getInstDatabyInstName,
  getDistance2:getDistance2,
  getAllDays4Month:getAllDays4Month,
  submitbook:submitbook,
  getOpenid:getOpenid,
  getToken:getToken,
  getUserInfo:getUserInfo,
  getPhoneInfo:getPhoneInfo,
  judgeUser:judgeUser,
  registerUser:registerUser,
  getBookInfo:getBookInfo,
  cancelBook:cancelBook,
  adToFavor:adToFavor,
  getFavorList:getFavorList,
  judgeFavor:judgeFavor,
  getMyInfo:getMyInfo
}